import json
import logging
import random
from django import http
from django.contrib.auth import authenticate,login
from django.shortcuts import render
from celery_tasks.sms.tasks import ccp_send_sms_code
from django.views import View
from django_redis import get_redis_connection

logger = logging.getLogger('django')

# from  import captcha
from verifications.libs.captcha.captcha import captcha
from celery_tasks.yuntongxun.ccp_sms import CCP


class ImageCodeView(View):
    # 图形验证码
    def get(self, request, uuid):
        # 生成图形验证码
        text, image = captcha.generate_captcha()

        # 保存图形验证码
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        # 响应图形验证码
        return http.HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    # 短信验证码
    def get(self, request, mobile):
        # 1.接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 2.校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 3.创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')

        # 4.提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码失效'})

        # 5.删除图形验证码,避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 6.对比图形验证码
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400, 'errmsg': '输入图形验证码有误'})

        # 从redis数据库获取存入的数据
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 判断是否存在
        if send_flag:
            return http.JsonResponse({'code': 400, 'errmsg': '获取短信过于频繁'})

        # 7.生成短信验证码:生成6位数字验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # #8.保存短信验证码
        # redis_conn.setex('sms_%s'% mobile,300,sms_code)
        #
        # #保存短信验证码的标志
        # redis_conn.serex('send_fiag_%s'% mobile,60,1)

        # 生成redis管道,一次提交多次请求
        pl = redis_conn.pipeline()
        # 添加redis请求队列
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('send_fiag_%s' % mobile, 60, 1)
        # 执行请求
        pl.execute()

        # 9.发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        ccp_send_sms_code.delay(mobile, sms_code)

        print('短信验证码:', sms_code)

        # 10.响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '发送短信成功'})


